package com.kye.express.business.customer_intro.add;

import android.Manifest;
import android.app.Dialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.databinding.DataBindingUtil;
import android.graphics.Rect;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

import com.afollestad.materialdialogs.MaterialDialog;
import com.jakewharton.rxbinding2.view.RxView;
import com.kye.addrpicker.AddressPickerActivity;
import com.kye.addrpicker.model.AddressPickerResult;
import com.kye.base.DebounceObservableTransformer;
import com.kye.base.Logger;
import com.kye.express.R;
import com.kye.express.business.base.BaseToolbarActivity;
import com.kye.express.business.customer_intro.CustomerIntroActivityContract;
import com.kye.express.business.waybill_take_photo.WaybillTakePhotoActivity;
import com.kye.express.business.web.KyeWebActivity;
import com.kye.express.config.KyeResAction;
import com.kye.express.databinding.ActivityCustomerIntroAddBinding;
import com.kye.express.databinding.ActivityCustomerIntroBinding;
import com.kye.express.utils.ScreenUtils;
import com.kye.express.utils.StringFormatUtils;
import com.kye.express.utils.StringUtils;
import com.kye.express.view.KyeProgressDialog;
import com.kye.express.view.ToastManager;
import com.kye.model.SharedPreferencesManager;
import com.kye.model.bean.customer_intro.AddCustomerIntroResultBean;
import com.kye.model.bean.customer_intro.GetCashCountResultBean;
import com.kye.model.bean.customer_intro.GetIntroInfoResultBean;
import com.kye.model.bean.customer_intro.IntroCompyModel;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadmoreListener;
import com.tbruyelle.rxpermissions2.Permission;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.functions.Consumer;
import me.drakeet.multitype.Items;
import me.drakeet.multitype.MultiTypeAdapter;

/**
 * 我要介绍
 */
public class CustomerIntroAddActivity extends BaseToolbarActivity implements CustomerIntroAddActivityContract.CustomerIntroAddActivityView {
    private ActivityCustomerIntroAddBinding mBinding;
    private CustomerIntroAddActivityContract.CustomerIntroAddActivityViewPresenter mPresenter;
    private MaterialDialog mTemplateDialog;
    private static final String KEY_SP_IS_SHOWED = "key_sp_is_showed";
    private static final String ARG_GUID = "guid";
    private static final String ARG_IS_EDIT_ALL = "is_edit_all";
    private static final int REQUEST_CODE_SELECT_AREA = 1;
    private static final int REQUEST_CODE_SELECT_CONTENT = 2;
    private Dialog mDialog;
    protected MultiTypeAdapter mAdapter;
    protected Items mDatas = new Items();
    private RxPermissions mRxPermissions;

    private String mGuid = "";
    private boolean mIsEditAll = true;//开发人员为空就是编辑全部，否则只能编辑备注

    public static void startActivity(Context context, String guid, boolean isEditAll) {
        Intent intent = new Intent(context, CustomerIntroAddActivity.class);
        if (!TextUtils.isEmpty(guid)) {
            intent.putExtra(ARG_GUID, guid);
            intent.putExtra(ARG_IS_EDIT_ALL, isEditAll);
        }
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_customer_intro_add);
        mBinding.setEditenable(mIsEditAll);
        mPresenter = new CustomerIntroAddActivityContract.CustomerIntroAddActivityViewPresenter(this);
        mPresenter.bind(this);
        setUpToolbar((Toolbar) findViewById(R.id.toolbar));
        mRxPermissions = new RxPermissions(this);
        initView();
        initEvent();
    }

    private void initView() {
        mGuid = getIntent().getStringExtra(ARG_GUID);
        mIsEditAll = getIntent().getBooleanExtra(ARG_IS_EDIT_ALL, true);

        if (TextUtils.isEmpty(mGuid)) {
            boolean showed = SharedPreferencesManager.get(KEY_SP_IS_SHOWED, false);
            if (!showed) {
                showTemplateDialog();
                SharedPreferencesManager.commit(KEY_SP_IS_SHOWED, true);
            }
        }

        mAdapter = new MultiTypeAdapter();
        mAdapter.register(IntroCompyModel.class, new IntroCompanyitemViewBinder(this));
        mBinding.recyclerview.setLayoutManager(new GridLayoutManager(this, 5));
        mBinding.recyclerview.addItemDecoration(new SpaceItemDecoration(ScreenUtils.dp2px(this, 8)));
        addCompanyDatas();
        mAdapter.setItems(mDatas);
        mBinding.recyclerview.setAdapter(mAdapter);
        mAdapter.notifyDataSetChanged();

        if (!TextUtils.isEmpty(mGuid)) {
            mPresenter.getIntroInfo(mGuid);
            setTitle(getString(R.string.customer_intro_edit_intro));
        } else {
            setTitle(getString(R.string.customer_intro_intro));
        }
    }

    private void addCompanyDatas() {
        mDatas.clear();
        List<IntroCompyModel> introCompyModels = new ArrayList<IntroCompyModel>();
        String[] expressList = getResources().getStringArray(R.array.intro_express_company);
        for (int i = 0; i < expressList.length; i++) {
            IntroCompyModel bean = new IntroCompyModel();
            bean.setName(expressList[i]);
            bean.setCheck(false);
            introCompyModels.add(bean);
        }
        mDatas.addAll(introCompyModels);
    }

    private void initEvent() {
        RxView.clicks(mBinding.myIntroduceTxtArea)
                .compose(new DebounceObservableTransformer<>())
                .compose(this.bindToLifecycleDestroy())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        AddressPickerActivity.startActivityForResult(CustomerIntroAddActivity.this, getString(R.string.customer_intro_select_area_two), AddressPickerActivity.Levels.city, REQUEST_CODE_SELECT_AREA);
                    }
                });

        RxView.clicks(mBinding.myIntroduceBtnSubmit)
                .compose(new DebounceObservableTransformer<>())
                .compose(this.bindToLifecycleDestroy())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        if (checkParams()) {
                            mPresenter.addCustomerIntro(mBinding, (List<IntroCompyModel>) mAdapter.getItems(), mGuid);
                        }
                    }
                });

        RxView.clicks(mBinding.ivContact)
                .compose(new DebounceObservableTransformer<>())
                .compose(this.bindToLifecycleDestroy())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        mRxPermissions.requestEach(Manifest.permission.READ_CONTACTS)
                                .subscribe(new Consumer<Permission>() {
                                    @Override
                                    public void accept(Permission permission) throws Exception {
                                        if (permission.granted) {
                                            Uri uri = ContactsContract.Contacts.CONTENT_URI;
                                            Intent intent = new Intent(Intent.ACTION_PICK, uri);
                                            startActivityForResult(intent, REQUEST_CODE_SELECT_CONTENT);
                                        } else {
                                            ToastManager.show(CustomerIntroAddActivity.this, R.string.customer_intro_no_read_contacts_permission, Toast.LENGTH_SHORT);
                                        }

                                    }
                                });
                    }
                });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK && data != null) {
            if (requestCode == REQUEST_CODE_SELECT_AREA) {
                AddressPickerResult resultAddress = (AddressPickerResult) data.getSerializableExtra(AddressPickerActivity.KEY_ARG_PICKED_RESULT);
                if (resultAddress != null) {
                    String address = resultAddress.getProvince() + resultAddress.getCity();
                    mBinding.myIntroduceTxtArea.setText(address);
                }
            } else if (requestCode == REQUEST_CODE_SELECT_CONTENT) {
                Uri uri = data.getData();
                if (uri != null) {
                    String[] contacts = getPhoneContacts(uri);
                    String number = "";
                    if (contacts != null) {
                        number = contacts[1];
                    }
                    if (!TextUtils.isEmpty(number)) {
                        number = number.replaceAll("-", "");
                        mBinding.myIntroduceEditPhone.setText(number);
                    }
                }
            }
        }
    }

    private String[] getPhoneContacts(Uri uri) {
        String[] contact = new String[2];
        //得到ContentResolver对象
        ContentResolver cr = getContentResolver();
        //取得电话本中开始一项的光标
        Cursor cursor = cr.query(uri, null, null, null, null);
        if (cursor != null) {
            cursor.moveToFirst();
            //取得联系人姓名
            int nameFieldColumnIndex = cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
            contact[0] = cursor.getString(nameFieldColumnIndex);
            //取得电话号码
            String ContactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
            Cursor phone = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
                    ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=" + ContactId, null, null);
            if (phone != null) {
                phone.moveToFirst();
                contact[1] = phone.getString(phone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
            }
            phone.close();
            cursor.close();
        } else {
            return null;
        }
        return contact;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mPresenter != null) {
            mPresenter.unbind();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_customer_intro_add, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        switch (id) {
            case R.id.menu_template:
                showTemplateDialog();
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    private void showTemplateDialog() {
        if (mTemplateDialog == null) {
            ImageView imageView = new ImageView(this);
            imageView.setImageResource(R.drawable.icon_customer_intro_template);
            mTemplateDialog = new MaterialDialog.Builder(this)
                    .title(R.string.customer_intro_template_dialog_title)
                    .customView(imageView, false)
                    .positiveText(R.string.common_know)
                    .show();
        } else {
            mTemplateDialog.show();
        }
    }

    private void showToast(String message) {
        ToastManager.show(CustomerIntroAddActivity.this, message, Toast.LENGTH_SHORT);
    }

    private void showToast(int res) {
        ToastManager.show(CustomerIntroAddActivity.this, res, Toast.LENGTH_SHORT);
    }

    private boolean checkParams() {
        if (TextUtils.isEmpty(mBinding.myIntroduceEditCompany.getText().toString())) {
            mBinding.myIntroduceEditCompany.requestFocus();
            showToast(R.string.customer_intro_input_company_name);
            return false;
        }
        if (mBinding.myIntroduceEditCompany.getText().toString().length() < 4 || StringFormatUtils.hasSpecialCharacters(mBinding.myIntroduceEditCompany.getText().toString())) {
            mBinding.myIntroduceEditCompany.requestFocus();
            showToast("请您输入正确的公司全称！");
            return false;
        }
        if (TextUtils.isEmpty(mBinding.myIntroduceEditName.getText().toString())) {
            showToast(R.string.customer_intro_input_name);
            mBinding.myIntroduceEditName.requestFocus();
            return false;
        }
        if (!StringFormatUtils.checkChineseLanguage(mBinding.myIntroduceEditName.getText().toString())) {
            showToast("请您输入正确的联系人姓名！");
            mBinding.myIntroduceEditName.requestFocus();
            return false;
        }
        if (TextUtils.isEmpty(mBinding.myIntroduceEditPsition.getText().toString())) {
            showToast(R.string.customer_intro_input_position);
            mBinding.myIntroduceEditPsition.requestFocus();
            return false;
        }
        if (!StringFormatUtils.checkChineseLanguage(mBinding.myIntroduceEditPsition.getText().toString())) {
            showToast("请您输入正确的联系人职位！");
            mBinding.myIntroduceEditPsition.requestFocus();
            return false;
        }
        if ((!mBinding.rbPrincipalYes.isChecked()) && (!mBinding.rbPrincipalNo.isChecked())) {
            showToast("请选择联系人是否为负责人");
            return false;
        }
        if (TextUtils.isEmpty(mBinding.myIntroduceEditPhone.getText().toString())) {
            showToast(R.string.customer_intro_input_right_phone);
            mBinding.myIntroduceEditPhone.requestFocus();
            return false;
        }
        if (!StringUtils.isMobileNO(mBinding.myIntroduceEditPhone.getText().toString())) {
            showToast(R.string.customer_intro_input_right_phone);
            mBinding.myIntroduceEditPhone.requestFocus();
            return false;
        }
        if (TextUtils.isEmpty(mBinding.myIntroduceTxtArea.getText().toString())) {
            showToast(R.string.customer_intro_select_area);
            return false;
        }
        if ((!mBinding.rbIntroYes.isChecked()) && (!mBinding.rbIntroNo.isChecked())) {
            showToast("请选择有无与联系人介绍跨越");
            return false;
        }
        if ((!mBinding.rbFriend.isChecked()) && (!mBinding.rbColleague.isChecked()) && (!mBinding.rbBusiness.isChecked())) {
            showToast("请选择与联系人关系");
            return false;
        }

        boolean isCheckCompany = false;
        List<IntroCompyModel> introCompyModels = (List<IntroCompyModel>) mAdapter.getItems();
        if (introCompyModels != null) {
            for (IntroCompyModel item : introCompyModels) {
                if (item.isCheck()) {
                    isCheckCompany = true;
                    break;
                }
            }
        }

        if (!isCheckCompany) {
            if (TextUtils.isEmpty(mBinding.edtOther.getText().toString())) {
                showToast("请选择主要发哪家快递公司");
                return false;
            }
        }
        return true;
    }

    @Override
    public void onComplete() {
        if (mDialog != null && mDialog.isShowing()) {
            mDialog.dismiss();
        }
    }

    @Override
    public void onLoading() {
        if (mDialog == null) {
            mDialog = new KyeProgressDialog.Builder(this).build();
        }
        mDialog.show();
    }

    @Override
    public void onLoaded(AddCustomerIntroResultBean addCustomerIntroResultBean) {
        String msg = "";
        if (TextUtils.isEmpty(mGuid)) {
            msg = getString(R.string.customer_intro_intro_successfully);
        } else {
            msg = getString(R.string.customer_intro_edit_successfully);
        }
        showToast(msg);
        finish();
    }

    @Override
    public void onOtherError(String msg) {
        showToast(msg);
        if (mDialog != null && mDialog.isShowing()) {
            mDialog.dismiss();
        }
    }

    @Override
    public void onApiError(String msg) {
        showToast(msg);
        if (mDialog != null && mDialog.isShowing()) {
            mDialog.dismiss();
        }
    }

    @Override
    public void onLoadedGetInfo(GetIntroInfoResultBean resultBean) {
        if (resultBean != null && mBinding != null) {
            mBinding.setData(resultBean);
            mBinding.setEditenable(mIsEditAll);
            List<IntroCompyModel> introCompyModels = (List<IntroCompyModel>) mAdapter.getItems();
            if (introCompyModels != null && introCompyModels.size() == 10) {
                introCompyModels.get(0).setCheck(resultBean.getIsSendSF() == 1);
                introCompyModels.get(1).setCheck(resultBean.getIsSendBD() == 1);
                introCompyModels.get(2).setCheck(resultBean.getIsSendLB() == 1);
                introCompyModels.get(3).setCheck(resultBean.getIsSendSE() == 1);
                introCompyModels.get(4).setCheck(resultBean.getIsSendYD() == 1);
                introCompyModels.get(5).setCheck(resultBean.getIsSendYT() == 1);
                introCompyModels.get(6).setCheck(resultBean.getIsSendST() == 1);
                introCompyModels.get(7).setCheck(resultBean.getIsSendZT() == 1);
                introCompyModels.get(8).setCheck(resultBean.getIsSendBS() == 1);
                introCompyModels.get(9).setCheck(resultBean.getIsSendAN() == 1);
                for (IntroCompyModel item : introCompyModels) {
                    item.setEditenable(mIsEditAll);
                }
            }

            mAdapter.notifyDataSetChanged();
        }
    }

    public class SpaceItemDecoration extends RecyclerView.ItemDecoration {

        private int space;

        public SpaceItemDecoration(int space) {
            this.space = space;
        }

        @Override
        public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
            outRect.left = space;
            outRect.bottom = space;
        }

    }
}
